package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.Tools;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.*;
import io.renren.modules.sys.service.AccountService;
import io.renren.modules.sys.service.AccountheadService;
import io.renren.modules.sys.service.AccountitemService;
import io.renren.modules.sys.service.DepotheadService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 账户信息
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:35
 */
@RestController
@RequestMapping("sys/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private DepotheadService depotheadService;
    @Autowired
    private AccountheadService accountheadService;
    @Autowired
    private AccountitemService accountitemService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:account:list")
    public R list(@RequestParam Map<String, Object> params){
//        limit page
        params.put("sidx","");
        params.put("order","asc");
        params.put("limit",params.get("rows"));
        PageUtils page = accountService.queryPage(params);

        return R.ok().put("total", page.getTotalCount()).put("rows",page.getList());
    }

    /**
     * 列表
     */
    @RequestMapping("/getAccount")
    public R getAccount(@RequestParam Map<String, Object> params){
//        limit page
        List<AccountEntity> accountList = accountService.selectList(new EntityWrapper<AccountEntity>().orderBy("Id"));
        return R.ok().put("accountList",accountList);
    }

    @RequestMapping("/findBy")
    public R findBy(@RequestParam Map<String, Object> params){
//        limit page
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if(pageSizeObj!=null){
            pageSize=pageSizeObj.toString();
        }
        if(pageNoObj!=null){
            pageNo=pageNoObj.toString();
        }
        params.put("limit",pageSize);
        params.put("page",pageNo);
        Page<AccountEntity> page = accountService.selectPage(
                new Query<AccountEntity>(params).getPage(),
                new EntityWrapper<AccountEntity>().like("name", Tools.dealNullStr(params.get("name")))
                        .like("serialNo",Tools.dealNullStr(params.get("serialNo")))
                        .like("remark", Tools.dealNullStr(params.get("remark")))
                        .orderBy("Id")
        );

        PageUtils pageUtils = new PageUtils(page);

        return R.ok().put("total",pageUtils.getTotalCount()).put("rows",pageUtils.getList());
    }

    /**
     * [{"Id":12,"AccountName":"上海农行"},{"Id":11,"AccountName":"微信"},{"Id":10,"AccountName":"支付宝"},{"Id":9,"AccountName":"流动总账"},{"Id":4,"AccountName":"南通建行"}]
     */
    @RequestMapping("/findBySelect")
    public JSONArray findBySelect(){
        Map<String, Object> params = new HashMap<>();
        params.put("order", "desc");
        PageUtils page = accountService.queryAccount(params);

        List<?> dataList = page.getList();
        JSONArray dataArray = new JSONArray();
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject item = new JSONObject();
            AccountEntity account = (AccountEntity) dataList.get(i);
            item.put("Id", account.getId());
            item.put("AccountName", account.getName()); //客户名称
            dataArray.add(item);
        }

        return dataArray;
    }

    @RequestMapping("/findAccountInOutList")
    @RequiresPermissions("sys:account:list")
    public R findAccountInOutList(@RequestParam Map<String, Object> params){
//        limit page
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        Integer pageNo = Integer.valueOf(params.get("pageNo").toString());
        Double initialAmount = Double.valueOf(params.get("initialAmount").toString());
        int start = pageSize*(pageNo-1);
        int end = pageSize*pageNo-1;
        params.put("start",start);
        params.put("end",end);
        List<AccountLiuShui> list = accountService.findAccountInOutList(params);
        String accountId = Tools.dealNullStr(params.get("accountId"));
        for(AccountLiuShui liuShui:list){

            String accountIdList = liuShui.getAList();
            String accountMoneyList = liuShui.getAmList();
            accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
            accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
            String[] aList = accountIdList.split(",");
            String[] amList = accountMoneyList.split(",");

            liuShui.setaAttr(aList);
            liuShui.setAmAttr(amList);

            String timeStr = liuShui.getoTime();
            Double balance = getAccountSum(accountId, timeStr) + getAccountSumByHead(accountId, timeStr)
                    + getAccountSumByDetail(accountId, timeStr) + getManyAccountSum(accountId, timeStr) + initialAmount;
            liuShui.setBalance(balance);
        }
        return R.ok().put("total", list.size()).put("rows",list);
    }

    private Double getManyAccountSum(String accountId, String timeStr) {
        Double accountSum = 0.00;
        List<DepotheadEntity> depotheadEntities = depotheadService.selectList(new EntityWrapper<DepotheadEntity>().like("AccountIdList", accountId).lt("OperTime", timeStr));
        for (DepotheadEntity depotHead : depotheadEntities) {
            String accountIdList = depotHead.getAccountidlist();
            String accountMoneyList = depotHead.getAccountmoneylist();
            accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
            accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
            String[] aList = accountIdList.split(",");
            String[] amList = accountMoneyList.split(",");
            for (int i = 0; i < aList.length; i++) {
                if (aList[i].toString().equals(accountId.toString())) {
                    accountSum = accountSum + Double.parseDouble(amList[i].toString());
                }
            }
        }
        return accountSum;
    }

    private Double getAccountSumByHead(String accountId, String timeStr) {
        Double accountSum = 0.00;
        List<AccountheadEntity> accountheadEntities = accountheadService.selectList(new EntityWrapper<AccountheadEntity>().eq("AccountId", accountId).lt("BillTime", timeStr));
        for (AccountheadEntity accountheadEntity:accountheadEntities
             ) {
            accountSum = accountSum + accountheadEntity.getChangeamount();
        }
        return accountSum;
    }

    private Double getAccountSumByDetail(String accountId, String timeStr) {
        Double accountSum = 0.00;
        List<AccountheadEntity> accountheadEntities = accountheadService.selectList(new EntityWrapper<AccountheadEntity>().lt("BillTime", timeStr));
        String ids = "";
        for (AccountheadEntity accountHead : accountheadEntities) {
            ids = ids + accountHead.getId() + ",";
        }
        if (!ids.equals("")) {
            ids = ids.substring(0, ids.length() - 1);
        }
        List<AccountitemEntity> accountitemEntities = accountitemService.selectList(new EntityWrapper<AccountitemEntity>().eq("AccountId", accountId).in("HeaderId", ids));
        for (AccountitemEntity accountItem : accountitemEntities) {
            accountSum = accountSum + accountItem.getEachamount();
        }
        return accountSum;
    }

    private Double getAccountSum(String accountId, String timeStr) {
        Double accountSum = 0.00;
        List<DepotheadEntity> depotheadEntities = depotheadService.selectList(new EntityWrapper<DepotheadEntity>().eq("AccountId", accountId).lt("OperTime", timeStr));
        for (DepotheadEntity depotHead : depotheadEntities) {
            accountSum = accountSum + depotHead.getChangeamount();
        }
        return accountSum;
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:account:info")
    public R info(@PathVariable("id") Long id){
        AccountEntity account = accountService.selectById(id);

        return R.ok().put("account", account);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:account:save")
    public R save(@RequestBody AccountEntity account){
        accountService.insert(account);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:account:update")
    public R update(@RequestBody AccountEntity account){
        ValidatorUtils.validateEntity(account);
        accountService.updateAllColumnById(account);//全部更新
        
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:account:delete")
    public R delete(@RequestBody Long[] ids){
        accountService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

}
